package com.haixiaoke.saas.contract.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fasc.open.api.bean.common.CorpIdentInfo;
import com.fasc.open.api.v5_1.res.corp.CorpIdentityInfoRes;
import com.fasc.open.api.v5_1.res.org.EmployeeInfo;
import com.haixiaoke.saas.common.constant.ContractConstants;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.contract.domain.Contract;
import com.haixiaoke.saas.contract.service.IContractService;
import com.haixiaoke.saas.fadada.service.FaDaDaService;
import com.haixiaoke.saas.tenant.domain.ElectronicVisa;
import com.haixiaoke.saas.tenant.service.IElectronicVisaService;
import com.haixiaoke.saas.tenant.service.ITenantService;
import com.haixiaoke.saas.house.service.IHouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 法大大回调服务
 *
 * @author panda
 * @Date 2024/6/13
 **/
@Slf4j
@Service
public class FaDaDaCallbackService {

    @Autowired
    private IElectronicVisaService electronicVisaService;
    @Autowired
    private FaDaDaService faDaDaService;
    @Autowired
    private IContractService contractService;

    /**
     * 处理回调
     *
     * @param map <a href="https://dev.fadada.com/api-doc/HZRSAZQXZR/0T8MZCFRRZTU646K/5-1"/>
     */
    @Transactional
    public void disposeCallback(Map<String, Object> map) {
        if (ObjectUtil.isNull(map)) {
            log.error("回调事件，map为空");
            return;
        }
        String event = map.get("event").toString();
        if (StrUtil.isBlank(event)) {
            log.error("回调事件，event事件为空");
            return;
        }
        switch (event) {
            case "corp-authorize":
                log.info("企业用户授权事件 data:{}", map);
                this.enterpriseAuth(map);
                break;
            case "sign-task-finished":
                log.info("签署任务完成事件 data:{}", map);
                this.finished(map);
                break;
            case "sign-task-expire":
                log.info("签署任务逾期 data:{}", map);
                this.expire(map);
                break;
        }

    }

    /**
     * 参与方填写事件
     *
     * @param map
     */
    private void filled(Map<String, Object> map) {
        String signTaskStatus = map.get("signTaskStatus").toString();
        // fill_progress：填写中（填写参与方进行填写）
        // fill_completed：填写已完成（填写的所有参与方已完成填写，但尚未定稿）
        // sign_progress：签署中 (签署参与方进行签署)
        if (StrUtil.equals("fill_completed", signTaskStatus) || StrUtil.equals("fill_progress", signTaskStatus)) {
            /*String signTaskId = map.get("signTaskId").toString();
            Map<String, Map<String, Object>> typeMap = lesseeContractService.selectByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(typeMap) || typeMap.isEmpty()) {
                log.error("参与方填写事件成功事件，填写合同不存在，signTaskId:{}", signTaskId);
                return;
            }
            if (typeMap.size() != 1) {
                log.error("参与方填写事件成功事件，流程id查出多条数据，{}", JSONObject.toJSONString(typeMap));
                return;
            }
            Map<String, Object> dataMap = null;
            for (Map.Entry<String, Map<String, Object>> entry : typeMap.entrySet()) {
                dataMap = entry.getValue();
            }
            if (dataMap == null) {
                log.error("参与方填写事件成功事件，合同数据获取异常，{}", JSONObject.toJSONString(typeMap));
                return;
            }
            // 合同id
            String contractId = dataMap.get("id").toString();
            // 签署类型:1.甲方;2.乙方
            String signType = "";
            // 合同类型:1,业主合同;2.租客合同;3.交割合同
            String contractType = "";
            // 身份标识,甲方、乙方
            String actorId = map.get("actorId").toString();
            if (StrUtil.equals("乙方", actorId)) {
                signType = TenantConstants.SIGN_TYPE_PARTY_B;
            } else if (StrUtil.equals("甲方", actorId)) {
                signType = TenantConstants.SIGN_TYPE_PARTY_A;
            }
            String type = dataMap.get("type").toString();
            switch (type) {
                case "1":
                    contractType = TenantConstants.CONTRACT_TYPE_LESSEE;
                    break;
                case "2":
                    contractType = TenantConstants.CONTRACT_TYPE_PROPRIETOR;
                    break;
                case "3":
                    contractType = TenantConstants.CONTRACT_TYPE_DELIVERY;
                    break;
            }

            ElectronicVisaSignProgress electronicVisaSignProgress = electronicVisaSignProgressService.selectSignProgressByName(
                    contractId, signType, contractType);
            if (ObjectUtil.isNotEmpty(electronicVisaSignProgress)) {
                electronicVisaSignProgress.setId(null);
                electronicVisaSignProgress.setSignProgress(TenantConstants.SIGN_PROGRESS_HAVE_FILLED);
                electronicVisaSignProgressService.insertElectronicVisaSignProgress(electronicVisaSignProgress);
            }*/
        }

    }

    private void expire(Map<String, Object> map) {
        String signTaskStatus = map.get("signTaskStatus").toString();
        // expired：已逾期
        if ("expired".equals(signTaskStatus)) {
            String signTaskId = map.get("signTaskId").toString();
            Contract contract = contractService.selectContractByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(contract)) {
                log.error("签署任务逾期事件，签署任务不存在，signTaskId:{}", signTaskId);
                return;
            }
            if (!StrUtil.equals(ContractConstants.CONTRACT_STATE_TO_BE_SIGNED, contract.getContractState())) {
                log.error("签署任务逾期事件，合同状态不正确，signTaskId:{}", signTaskId);
                return;
            }
            Contract newContract = new Contract();
            newContract.setContractId(contract.getContractId());
            newContract.setContractState(ContractConstants.CONTRACT_STATE_CANCELED);
            newContract.setUpdateTime(DateUtil.date());
            contractService.updateContract(newContract);
        }
    }

    /**
     * 签署任务撤销
     *
     * @param map
     */
    private void canceled(Map<String, Object> map) {
       /* String signTaskStatus = map.get("signTaskStatus").toString();
        if ("task_terminated".equals(signTaskStatus)) {
            String signTaskId = map.get("signTaskId").toString();
            String terminationNote = null;
            if (map.containsKey("terminationNote")) {
                terminationNote = map.get("terminationNote").toString();
            }
            Map<String, Map<String, Object>> typeMap = lesseeContractService.selectByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(typeMap) || typeMap.isEmpty()) {
                log.error("签署任务撤销事件，签署任务不存在，signTaskId:{}", signTaskId);
                return;
            }
            if (typeMap.size() != 1) {
                log.error("签署任务逾期事件，流程id查出多条数据，{}", JSONObject.toJSONString(typeMap));
                return;
            }
            Map<String, Object> dataMap = null;
            for (Map.Entry<String, Map<String, Object>> entry : typeMap.entrySet()) {
                dataMap = entry.getValue();
            }
            if (dataMap == null) {
                log.error("参与方填写事件成功事件，合同数据获取异常，{}", JSONObject.toJSONString(typeMap));
                return;
            }
            String type = dataMap.get("type").toString();
            switch (type) {
                case "1":
                    LesseeContract lesseeContract = new LesseeContract();
                    lesseeContract.setLesseeContractId(dataMap.get("id").toString());
                    lesseeContract.setLesseeContractStatus(ContractConstants.LESSEE_CONTRACT_STATUS_TERMINATED);
                    if (ObjectUtil.isNotNull(terminationNote)) {
                        lesseeContract.setRemark(terminationNote);
                    }
                    lesseeContractService.updateLesseeContract(lesseeContract);
                    break;
                case "2":
                    ProprietorContract proprietorContract = new ProprietorContract();
                    proprietorContract.setProprietorContractId(dataMap.get("id").toString());
                    proprietorContract.setContractStatus(ProprietorContractEnum.CONTRACT_STATUS_TERMINATION.getValue());
                    if (ObjectUtil.isNotNull(terminationNote)) {
                        proprietorContract.setRemark(terminationNote);
                    }
                    proprietorContractService.updateProprietorContract(proprietorContract);
                    break;
                case "3":
                    DeliveryOrder deliveryOrder = new DeliveryOrder();
                    deliveryOrder.setDeliveryOrderId(dataMap.get("id").toString());
                    deliveryOrder.setDeliveryOrderStatus(ContractConstants.DELIVERY_ORDER_STATUS_TERMINATION);
                    if (ObjectUtil.isNotNull(terminationNote)) {
                        deliveryOrder.setRemark(terminationNote);
                    }
                    deliveryOrderService.updateDeliveryOrder(deliveryOrder);
                    break;
            }
        }*/
    }

    /**
     * 拒签事件
     *
     * @param map
     */
    private void visaRejected(Map<String, Object> map) {
        String actorId = map.get("actorId").toString();
        /*if (StrUtil.equals("乙方", actorId)) {
            String signTaskId = map.get("signTaskId").toString();
            Map<String, Map<String, Object>> typeMap = lesseeContractService.selectByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(typeMap) || typeMap.isEmpty()) {
                log.error("参与方拒签事件，签署任务不存在，signTaskId:{}", signTaskId);
                return;
            }
            if (typeMap.size() != 1) {
                log.error("参与方拒签事件，流程id查出多条数据，{}", JSONObject.toJSONString(typeMap));
                return;
            }
            Map<String, Object> dataMap = null;
            for (Map.Entry<String, Map<String, Object>> entry : typeMap.entrySet()) {
                dataMap = entry.getValue();
            }
            if (dataMap == null) {
                log.error("参与方拒签事件，合同数据获取异常，{}", JSONObject.toJSONString(typeMap));
                return;
            }
            String type = dataMap.get("type").toString();
            switch (type) {
                case "1":
                    LesseeContract lesseeContract = new LesseeContract();
                    lesseeContract.setLesseeContractId(dataMap.get("id").toString());
                    lesseeContract.setLesseeContractStatus(ContractConstants.LESSEE_CONTRACT_STATUS_TERMINATED);
                    lesseeContract.setUpdateTime(DateUtils.getNowDate());
                    lesseeContractService.updateLesseeContract(lesseeContract);
                    break;
                case "2":
                    ProprietorContract proprietorContract = new ProprietorContract();
                    proprietorContract.setProprietorContractId(dataMap.get("id").toString());
                    proprietorContract.setContractStatus(ProprietorContractEnum.CONTRACT_STATUS_TERMINATION.getValue());
                    proprietorContract.setUpdateTime(DateUtils.getNowDate());
                    proprietorContractService.updateProprietorContract(proprietorContract);
                    break;
                case "3":
                    DeliveryOrder deliveryOrder = new DeliveryOrder();
                    deliveryOrder.setDeliveryOrderId(dataMap.get("id").toString());
                    deliveryOrder.setDeliveryOrderStatus(ContractConstants.DELIVERY_ORDER_STATUS_TERMINATION);
                    deliveryOrder.setUpdateTime(DateUtils.getNowDate());
                    deliveryOrderService.updateDeliveryOrder(deliveryOrder);
                    break;
            }
        }*/
    }

    public void finished(Map<String, Object> map) {

        String signTaskStatus = map.get("signTaskStatus").toString();
        // sign_progress：签署中 (签署参与方进行签署)
        // sign_completed：签署已完成 (签署所有参与方均已签署完成)
        // task_finished：任务已完成 (签署任务已成功结束)
        if (StrUtil.equals("task_finished", signTaskStatus)) {

            String signTaskId = map.get("signTaskId").toString();
            Contract contract = contractService.selectContractByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(contract)) {
                log.error("签署任务完成事件，签署任务不存在，signTaskId:{}", signTaskId);
                return;
            }
            if (!StrUtil.equals(ContractConstants.CONTRACT_STATE_TO_BE_SIGNED, contract.getContractState())) {
                log.error("签署任务完成事件，合同状态不正确，signTaskId:{}", signTaskId);
                return;
            }
            Contract newContract = new Contract();
            newContract.setContractId(contract.getContractId());
            newContract.setContractState(ContractConstants.CONTRACT_STATE_SIGN_OFF);
            newContract.setUpdateTime(DateUtils.getNowDate());
            contractService.updateContract(newContract);

        }
    }

    /**
     * 签署任务参与方签署成功事件
     *
     * @param map
     */
    private void signed(Map<String, Object> map) {

        // String signTaskStatus = map.get("signTaskStatus").toString();
        // sign_progress：签署中 (签署参与方进行签署)
        // sign_completed：签署已完成 (签署所有参与方均已签署完成)
        // task_finished：任务已完成 (签署任务已成功结束)
        String signTaskId = map.get("signTaskId").toString();
        Contract contract = contractService.selectContractByFlowId(signTaskId);
        if (ObjectUtil.isEmpty(contract)) {
            log.error("签署任务参与方签署成功事件，签署任务不存在，signTaskId:{}", signTaskId);
            return;
        }
        // 签署类型:1.甲方;2.乙方
        String signType = "";
        // 合同类型:1,业主合同;2.租客合同
        String contractType = "";
        // 身份标识,甲方、乙方
        String actorId = map.get("actorId").toString();
        /*if (StrUtil.equals("乙方", actorId)) {
            signType = TenantConstants.SIGN_TYPE_PARTY_B;
            contract.setPartyBSignFlag(ContractConstants.HAVE_SIGNED_FLAG);
        } else if (StrUtil.equals("甲方", actorId)) {
            signType = TenantConstants.SIGN_TYPE_PARTY_A;
            contract.setPartyASignFlag(ContractConstants.HAVE_SIGNED_FLAG);
        }
        contract.setUpdateTime(DateUtils.getNowDate());
        contract.setLesseeContractId(contractId);
        contractService.updateContract(lesseeContract);*/
    }

    /**
     * 企业用户授权事件
     *
     * @param map
     */
    public void enterpriseAuth(Map<String, Object> map) {
        String authResult = map.get("authResult").toString();
        if ("success".equals(authResult)) {
            String clientCorpId = map.get("clientCorpId").toString();
            String openCorpId = map.get("openCorpId").toString();

            ElectronicVisa electronicVisa = electronicVisaService.selectElectronicVisaByTenantId(clientCorpId);
            if (ObjectUtil.isEmpty(electronicVisa)) {
                log.error("企业用户授权事件，签署任务不存在，clientCorpId:{}", clientCorpId);
                return;
            }
            electronicVisa.setOpenId(openCorpId);
            try {
                CorpIdentityInfoRes corpIdentityInfoRes = faDaDaService.corpGetIdentityInfo(openCorpId);
                CorpIdentInfo corpIdentInfo = corpIdentityInfoRes.getCorpIdentInfo();
                electronicVisa.setOrganizationName(corpIdentInfo.getCorpName());
                electronicVisa.setSocialCreditCode(corpIdentInfo.getCorpIdentNo());

                List<EmployeeInfo> corpMemberList = faDaDaService.getCorpMemberList(openCorpId);
                EmployeeInfo employeeInfo = corpMemberList.get(0);
                Long memberId = employeeInfo.getMemberId();
                electronicVisa.setProxyOperatorOpenid(memberId.toString());
                electronicVisa.setAuthType(TenantConstants.AUTH_TYPE_YES);
                electronicVisaService.updateElectronicVisa(electronicVisa);

            } catch (Exception e) {
                log.error("企业用户授权事件，获取企业信息失败:{}", e.getMessage(), e);
            }
        }
    }
}
